package com.wisdytech.common.websocket.handler;


import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import com.wisdytech.linkdcs.configuration.service.ITtEqConfigurationService;
import com.wisdytech.linkdcs.system.model.SysUser;

/**
 * websocket通知类
 * @author dlb
 */
public class WebSocketPushHandler extends TextWebSocketHandler{
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource
	private ITtEqConfigurationService eqConfigurationService;
	
	
	/**
	 * 缓存websocekt列表
	 */
	public static final ConcurrentHashMap<String, WebSocketSession> userSessionLists=
			new ConcurrentHashMap<>();
	
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		
		String key =(String)session.getAttributes().get("time");
		
		if (session.isOpen()) {
            session.close();
        }
		if(userSessionLists.containsKey(key)) {
			userSessionLists.remove(key);
		}
		
		
        logger.info("用户退出系统。。。");
	}

	
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		
        logger.info("用户信息:" + session.getAttributes());
        
        Object time =session.getAttributes().get("time");
        if(null != time) {
        	 String key =(String) time;
        	 //缓存
             userSessionLists.put(key, session);
        }
        
       
        
       
	}

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		 String key=(String)session.getAttributes().get("time");
		
		logger.info("系统处理用户的请求信息。。。"+message.getPayload());
		//更新用户保存的组态信息
		if(userSessionLists.containsKey(key)) {
			//更新组态id
			userSessionLists.get(key).getAttributes().put("zutaiId", message.getPayload());
		}

	}
	
	
	
	

}
